package com.xwaiy.xwaiyrpc.springboot.starter.bootstrap;

import com.xwaiy.xwaiyrpc.RpcApplication;
import com.xwaiy.xwaiyrpc.config.RegistryConfig;
import com.xwaiy.xwaiyrpc.config.RpcConfig;
import com.xwaiy.xwaiyrpc.exception.RpcException;
import com.xwaiy.xwaiyrpc.exception.enums.ErrorCode;
import com.xwaiy.xwaiyrpc.model.ServiceMetaInfo;
import com.xwaiy.xwaiyrpc.registry.LocalRegistry;
import com.xwaiy.xwaiyrpc.registry.Registry;
import com.xwaiy.xwaiyrpc.registry.RegistryFactory;
import com.xwaiy.xwaiyrpc.springboot.starter.annotation.RpcService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

/**
 * 服务端启动
 * @Author Xwaiy
 * @Date 2025/9/5 12:30
 **/
@Slf4j
public class RpcServerBootstrap implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        Class<?> beanClass = bean.getClass();
        RpcService rpcService = beanClass.getAnnotation(RpcService.class);

        if (rpcService != null) {
            // TO 获取服务基本信息
            Class<?> interfaceClass = rpcService.interfaceClass();
            // 默认值
            if(interfaceClass == void.class){
                interfaceClass = beanClass.getInterfaces()[0];
            }
            String serviceName = interfaceClass.getName();
            String serviceVersion = rpcService.serviceVersion();

            // TO 本地注册服务
            LocalRegistry.registerService(serviceName, bean);

            // TO 全局配置
            final RpcConfig rpcConfig = RpcApplication.getRpcConfig();

            // TO 注册到注册中心
            RegistryConfig registryConfig = rpcConfig.getRegistryConfig();
            Registry registry = RegistryFactory.getInstance(registryConfig.getRegistry());
            ServiceMetaInfo serviceMetaInfo = new ServiceMetaInfo();
            serviceMetaInfo.setServiceName(serviceName);
            serviceMetaInfo.setVersion(serviceVersion);
            serviceMetaInfo.setServiceHost(rpcConfig.getServerHost());
            serviceMetaInfo.setServicePort(rpcConfig.getServerPort());

            try{
                registry.register(serviceMetaInfo);
            }catch (Exception e){
                log.error("register registry error:{}",e);
                throw new RpcException(ErrorCode.REGISTRY_SERVICE_REGISTER_FAILED, "register registry error",e);
            }
        }

        return BeanPostProcessor.super.postProcessBeforeInitialization(bean, beanName);
    }
}
